/*
* @Author: Josh
* @Date:   2019-01-21 15:46:54
* @Last Modified by:   Administrator
* @Last Modified time: 2019-06-02 17:16:46
*/

'use strict';
require('./index.css');
require('page/common/nav-simple/index.js');
var _mall = require('util/mall.js'),
    _user = require('service/user-service.js');

//表单里的错误提示
var formError = {
    show : function(errMsg){
        $('.error-item').show().find('.err-msg').text(errMsg);
    },
    hide : function(){
        $('.error-item').hide().find('.err-msg').text('');
    }
};

//page 逻辑部分
var page = {
    init : function(){
        this.bindEvent();
    },
    bindEvent : function(){
        var _this = this;
        //登录按钮点击事件
        $('#submit').click(function(){
            _this.submit();
        });
        //键盘回车输入事件
        $('.user-content').keyup(function(e){
            //keyCode为回车键
            if(e.keyCode === 13){
                _this.submit();
            }
        });
    },
    //提交表单
    submit : function(){
        var formData = {
                username : $.trim($('#username').val()),
                password : $.trim($('#password').val())
            },
            //表单验证结果
            validateResult = this.formValidate(formData);

        //验证成功
        if(validateResult.status){
            //提交
            _user.login(formData, function(res){
                window.location.href = _mall.getUrlParam('redirect') || './index.html';
            }, function(errMsg){
                formError.show(errMsg);
            });
        }
        //验证失败
        else{
            //错误提示
            formError.show(validateResult.msg);
        }

    },
    //表单字段的验证
    formValidate : function(formData){
        var result = {
            status : false,
            msg    : '',
        };
        //密码或用户名为空判断
        if(!_mall.validate(formData.username, 'require')){
            result.msg = '用户名不能为空';
        }
        else if(!_mall.validate(formData.password, 'require')){
            result.msg = '密码不能为空';
        }
        else{
             //通过验证，返回正确提示
            result.status = true;
            result.msg    = '验证成功';
        }
        return result;
    }
};

$(function(){
    page.init(); 
});
